/**
 * 
 */
package com.csair.youth.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.csair.youth.constant.Constant;
import com.csair.youth.dao.impl.hibernate3.PermissionDaoImpl;
import com.csair.youth.dao.impl.hibernate3.RolePermissionDaoImpl;
import com.csair.youth.database.Permission;
import com.csair.youth.database.RolePermission;

/**
 * @author mickey
 *
 */
public class PermissionServiceImpl {
	private PermissionDaoImpl pdao;
	private RolePermissionDaoImpl rpdao;

	public PermissionDaoImpl getPdao() {
		return pdao;
	}
	public void setPdao(PermissionDaoImpl pdao) {
		this.pdao = pdao;
	}
	public RolePermissionDaoImpl getRpdao() {
		return rpdao;
	}
	public void setRpdao(RolePermissionDaoImpl rpdao) {
		this.rpdao = rpdao;
	}
	
	public void savePermission(Permission item){
		if(item == null) return;
		if(StringUtils.isEmpty(item.getId())) item.setId(null);
		pdao.saveOrUpdate(item);
	}
	
	public void deletePermissionById(String id){
		if(!StringUtils.isEmpty(id)) pdao.deleteById(id);
	}
	
	public Permission getPermission(String id){
		return pdao.findById(id);
	}
	
	public List getAllPermissions(){
		return pdao.findAllList();
	}
	
	public List getPermissionsByRoleId(String roleId){
		List list = rpdao.findByRoleId(roleId);
		if(list == null || list.size() == 0){
			return null;
		}
		int size = list.size();
		String pids[] = new String[size];
		for(int i=0; i<size; i++){
			RolePermission rp = (RolePermission)list.get(i);
			pids[i] = rp.getPermissionId();
		}
		return pdao.findPermissionsByIds(pids);
	}
	
	public Permission getPermissionByURL(String url){
		return pdao.findFirstPermissionByURL(url);
	}
	
	public void initGlobalPermissions(){
		if(getPermissionByURL(Constant.PERMISSION_AUDIT_EMAIL_URL) == null){
			Permission pp = new Permission();
			pp.setName(Constant.PERMISSION_AUDIT_EMAIL_NAME);
			pp.setDescription("选择此权限者，在有新资源上传后会收到审核邮件~请勿修改URL!!!");
			pp.setUrl(Constant.PERMISSION_AUDIT_EMAIL_URL);
			savePermission(pp);
		}
	}
	
}
